import leetcodeHis.算法总纲.链表.ListNode;

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache {

    private int capacity;
    private LinkedHashMap<Integer, Integer> linkedHashMap;

    public LRUCache(int capacity) {
        this.capacity = capacity;
    }

    public int get(int key) {
        int result = -1;
        if(linkedHashMap.get(key) != null) {
            result = linkedHashMap.get(key);
            linkedHashMap.remove(key);
            put(key, result);
        }
        return result;
    }

    void put(int key, int value) {
        if(linkedHashMap.get(key)!=null) {
            linkedHashMap.remove(key);
        }
        if(linkedHashMap.size() == capacity) {
            int oldKey = -1;
            for (Map.Entry<Integer, Integer> entry : linkedHashMap.entrySet()) {
                oldKey = entry.getKey();
                break;
            }
            linkedHashMap.remove(oldKey);
        }
        linkedHashMap.put(key, value);
    }

    public static void main(String[] args) {
        LRUCache cache = new LRUCache(2);

        cache.get(2);

        cache.put(2,6);
        cache.get(1);
        cache.put(1,5);
        cache.put(1,2);

        cache.get(1);
        cache.get(2);
    }
}
